﻿using System;
using System.Web.Security;
using DeJC.BLL.Utilities;
using DeJC.DAL.Model;
using DeJC.BLL;

namespace WEB.Infrastructure.CustomSecurity
{
    public class CustomMembershipProvider : MembershipProvider
    {

        #region Implemented
        public override bool RequiresUniqueEmail
        {
            get { return true; }
        }
        public override MembershipPasswordFormat PasswordFormat
        {
            get { throw new NotImplementedException(); }
        }
        public override int MaxInvalidPasswordAttempts
        {
            get { return 3; }
        }
        public override int MinRequiredPasswordLength
        {
            get { return 10; }
        }


        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            var args = new ValidatePasswordEventArgs(username, password, true);
            OnValidatingPassword(args);

            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            MembershipUser user = GetUser(username, true);

            if (user == null)
            {
                var newUser = new User()
                                  {
                                      UserName = username,
                                      Password = Encrypt.Sha256Encrypt(password),
                                      Email = username,
                                      CreationDate = DateTime.Now,
                                      LastLogin = DateTime.Now,
                                      TryLoginCount = 0,
                                      Enabled = false,
                                      IsActive = false,
                                      ActivationCode = Guid.NewGuid().ToString()
                                  };

                using (var unitOfWork = new UnitOfWork())
                {
                    unitOfWork.UserRepository.Add(newUser);
                    unitOfWork.Save();
                }

                status = MembershipCreateStatus.Success;
                return GetUser(username, true);

            }

            status = MembershipCreateStatus.DuplicateUserName;
            return null;
        }

        public override bool ValidateUser(string username, string password)
        {
            using (var unitOfWork = new UnitOfWork())
            {
                var usuario = unitOfWork.UserRepository.GetUser(username, password);
                if (usuario != null)
                    return true;
                return false;
            }

        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            using (var unitOfWork = new UnitOfWork())
            {
                var user = unitOfWork.UserRepository.GetUser(username);
                if (user != null)
                {
                    var membershipUser = new MembershipUser("CustomMembershipProvider", username,
                                                                       user.ID, user.UserName,
                                                                       string.Empty, string.Empty, true, false,
                                                                       user.CreationDate, user.LastLogin,
                                                                       DateTime.MinValue, DateTime.Now, DateTime.Now);

                    return membershipUser;
                }

            }
            return null;
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            using (var unitOfWork = new UnitOfWork())
            {
                var user = unitOfWork.UserRepository.GetUser(providerUserKey);
                if (user != null)
                {
                    bool indUsuarioValidado = user.IsActive;
                    bool indUsuarioBloquiado = user.Enabled;

                    var membershipUser = new MembershipUser("CustomMembershipProvider", user.UserName,
                                                                       providerUserKey, user.Email,
                                                                       string.Empty, string.Empty, indUsuarioValidado, indUsuarioBloquiado,
                                                                       user.CreationDate, user.LastLogin,
                                                                       DateTime.MinValue, DateTime.Now, DateTime.Now);

                    return membershipUser;
                }

            }
            return null;
        }

        public override void UpdateUser(MembershipUser user)
        {
            using (var unitOfWork = new UnitOfWork())
            {
                var usuario = unitOfWork.UserRepository.GetUser(user.UserName);

                usuario.LastLogin = user.LastLoginDate;
                usuario.IsActive = user.IsApproved;
                usuario.Enabled= user.IsLockedOut;

                unitOfWork.UserRepository.Update(usuario);
                unitOfWork.Save();
            }
        }
        #endregion




        #region Overrides of MembershipProvider


        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            throw new NotImplementedException();
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException();
        }
        
        public override string GetUserNameByEmail(string email)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override bool EnablePasswordRetrieval
        {
            get { throw new NotImplementedException(); }
        }

        public override bool EnablePasswordReset
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { throw new NotImplementedException(); }
        }

        public override string ApplicationName { get; set; }
        
        public override int PasswordAttemptWindow
        {
            get { throw new NotImplementedException(); }
        }
        
        public override int MinRequiredNonAlphanumericCharacters
        {
            get { throw new NotImplementedException(); }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new NotImplementedException(); }
        }

        #endregion
    }
}